<template>
  <div>
    <div>
      <el-input style="width: 200px; " placeholder="请输入用户名" v-model="username"/>
      <el-input style="width: 200px;margin: 0px 5px" placeholder="请输入姓名" v-model="name"/>
      <el-button type="primary" @click="getTableData(1)">搜索</el-button>
      <el-button type="primary" @click="resetData">重置</el-button>
    </div>
    <div style="margin: 5px 0px">
      <el-button type="primary" plain @click="addUser">新增</el-button>
      <el-button type="danger" plain @click="delBatch">删除</el-button>
      <el-button type="info" plain @click="exportExcel">批量导出</el-button>
      <el-upload style="display: inline-block;margin-left: 10px"
                 :action="$baseUrl+'/user/import'"
                 :headers="{token:user.token}"
                 :show-file-list="false"
                 :on-success="handleImport"
      >
        <el-button type="info" plain>批量导入</el-button>
      </el-upload>
    </div>
    <el-table :data="tableData" stripe :header-cell-style="{background:'#df6e2c',color:'white'}"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="序号" align="center"></el-table-column>
      <el-table-column prop="username" label="用户名" align="center"></el-table-column>
      <el-table-column prop="name" label="姓名" align="center"></el-table-column>
      <el-table-column prop="phone" label="手机号码" align="center"></el-table-column>
      <el-table-column prop="email" label="邮箱地址" align="center"></el-table-column>
      <el-table-column prop="address" label="地址" align="center"></el-table-column>
      <el-table-column label="头像" align="center">
        <template v-slot="scope">
          <div>
            <el-image :src="scope.row.avatar"
                      :preview-src-list="[scope.row.avatar]"
                      style="height: 40px ; width: 40px;border-radius: 50%"
                      v-if="scope.row.avatar" />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="role" label="角色" align="center"></el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template v-slot="scope">
          <el-button type="primary" size="mini" plain @click="editUser(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" plain @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="用户信息" :visible="formVisible" width="30%" >
      <el-form :model="form" label-width="80px" style="padding-right: 20px" :rules="rules" ref="VisibleRef">
        <el-form-item label="用户名" prop="username" >
          <el-input v-model="form.username" :disabled="form.id?true:false" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name" >
          <el-input v-model="form.name"  placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone" >
          <el-input v-model="form.phone"  placeholder="手机号码"></el-input>
        </el-form-item>
        <el-form-item label="邮箱地址" prop="email" >
          <el-input v-model="form.email"  placeholder="邮箱地址"></el-input>
        </el-form-item>
        <el-form-item label="住址" prop="address" >
          <el-input v-model="form.address"  placeholder="address"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role" >
          <el-radio-group v-model="form.role">
            <el-radio label="用户"></el-radio>
            <el-radio label="商家"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="头像" prop="role">
          <el-upload
              class="avatar-uploader"
              :action="$baseUrl+'/file/upload'"
              :headers={token:user.token}
              :on-success="handleAvatarSuccess"
              :file-list="form.avatar && form.avatar"
              list-type="picture"
          >
            <el-button type="primary">上传头像</el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "User",
  data(){
    return {
      ids:[],
      tableData:[],
      pageNum:1,  //当前页码数
      pageSize:5, //每页显示多少条数据
      total:0,
      username:'',
      name:'',
      formVisible:false,
      form:{},
      user:JSON.parse(localStorage.getItem("user") || '{}'),
      rules: {
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
      }
    }
  },
  methods:{
    handleImport(res,file,fileList){
      if (res.code==="200"){
        this.$message.success("导入数据成功")
        this.getTableData(1)
      }else {
        this.$message.error(res.msg)
      }
    },
    exportExcel(){
      if (!this.ids.length){
        window.open(`${this.$baseUrl}/user/export?token=${this.user.token}&username=${this.username}&name=${this.name}`)
      }else {
        let idsArr = this.ids.join(",") //将数组转换为字符串
        window.open(`${this.$baseUrl}/user/export?token=${this.user.token}&ids=${idsArr}`)
      }

    },
    getTableData(pageNum){
      if (pageNum) this.pageNum=pageNum
      this.$request.get("/user/selectByPage",{
       params:{
         pageNum:this.pageNum,
         pageSize:this.pageSize,
         name:this.name,
         username:this.username
       }
      }).then(res=>{　　　　
        this.tableData=res.data.records
        this.total=res.data.total
      })
    },
    handleCurrentChange(pageNum){
      this.getTableData(pageNum)
    },
    resetData(){
      this.name=''
      this.username=''
      this.getTableData(1)
    },
    handleAvatarSuccess(response,file,fileList){
      console.log(response,this.user)
      this.form.avatar=response.data
    },
    save(){
      this.$refs['VisibleRef'].validate(valid=>{
        if (valid){
          this.$request({
            url:this.form.id?'/user/update':'/user/add',
            method:"post",
            data:this.form
          }).then(res=>{
            if (res.code==='200'){
              this.$message.success('保存成功')
              this.getTableData()
              this.formVisible =false
            }else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    addUser(){
      this.form={}
      this.formVisible=true
    },
    editUser(user){
      this.form= {...user}
      this.formVisible=true
    },
    del(id) {
      this.$confirm("确定删除吗？","确定删除",{type:"warning"}).then(resp=>{
        this.$request.post('/user/delete/'+id).then(res=>{
          if (res.code==='200'){
            this.$message.success("删除成功")
            this.getTableData(1)
          }else {
            this.$message.error(res.msg)
          }
        })
      }).catch(error => {})
    },
    handleSelectionChange(v){
      this.ids= v.map(res=>res.id)
    },
    delBatch(){
      if (this.ids.length<=0){
        this.$message.info("请选择您要删除的数据")
        return
      }
      this.$confirm("确定批量删除吗?","确认删除",{type:"warning"}).then(resp=>{
        this.$request.post("/user/delete/batch",this.ids).then(res=>{
          if (res.code==='200'){
            this.$message.success("删除数据成功")
            this.getTableData(1)
          }else {
            this.$message.error("删除数据失败")
          }
        })
      }).catch(err=>{})
    }
  },
  mounted() {
    this.getTableData()
  }
}
</script>

<style scoped>

</style>